const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const moment = require('moment');

const AuthorSchema = new Schema({
    first_name: {type: String, required: true, max: 100},
    family_name: {type: String, required: true, max: 100},
    date_of_birth: {type: Date},
    date_of_death: {type: Date}
});

//virtual property

AuthorSchema.virtual('name').get(function () {
    return this.family_name + ',' + this.first_name;
});

AuthorSchema.virtual('lifespan').get(function () {
    return (this.date_of_death.getFullYear() - this.date_of_birth.getFullYear()) + '';
});

AuthorSchema.virtual('url').get(function () {
    return '/catalog/author/' + this._id;
});

AuthorSchema.virtual('birth_death').get(function () {
    return (this.date_of_birth ? moment(this.date_of_birth).format('YYYY-MM-DD') : '暂无')
        + (this.date_of_death ? '---' + moment(this.date_of_death).format('YYYY-MM-DD') : '')
});

module.exports = mongoose.model('Author', AuthorSchema);